import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useTokenStore } from '@/stores/token.js'
import router from '@/router'

// 使用相对路径，配合Vite代理
const baseURL = '/api'
const instance = axios.create({ baseURL })

instance.interceptors.request.use(
    (config) => {
        const tokenStore = useTokenStore()
        if (tokenStore.token) {
            config.headers.Authorization = tokenStore.token.token
        }
        return config
    },
    (err) => {
        return Promise.reject(err)
    }
)

instance.interceptors.response.use(
    result => {
        // 对于下载文件的请求，直接返回响应
        if (result.config.responseType === 'blob') {
            return result
        }
        
        if (result.data.code === 1) {
            return result.data
        } else {
            ElMessage.error(result.data.message ? result.data.message : '服务异常')
            return Promise.reject(result.data)
        }

    },
    err => {
        if (err.response.status === 401) {
            ElMessage.error('请先登录')
            router.push('/login')
        } else {
            ElMessage.error('服务异常')
            return Promise.reject(err)
        }
    }
)

export default instance